const app = getApp();
const config = require('../../../config/config.js');
const util = require('../../../utils/util.js');
const totalDot = 3,
  applicationDownPath = 'https://www.shencheyi.com/Download/3D8489EF-8B07-4D1B-BD76-3AD0164F46CA.jpg',
  templateListText = ['编辑信息', '车辆行驶证', '车辆登记证', '车辆完税证明', '机动车牌申请表'];
Page({

  data: {
    isShowDemo: false,
    demoSrc: '',
    currentTapPic:'',
    carId: '',
    templateList: ['vehicleInfoEdit', 'license', 'registration', 'certificate', 'application'],
    templateDataList: [{
        imageUrl: '../../../images/addcar.png',
        licencePlate: '', //车牌号码
        owner: '', //车辆所属人
        phoneNumber: '', //联系电话
        carDiscernCode: '', //车辆识别代号
        carEngineNumber: '', //车辆发动机号
        carSeats: '', //车辆核定载客人数
        /*单选 */
        carBelongList: ['私人户口', '公司户口'],
        carBelongType: '',
        carTypeList: [],
        carTypeId: '',
        carTypeName: '',

        isPanelShow: false,
        keyBoardType: 1,
        licenceProvince: '粤',
        licenceCode: '',


      }, {
        //车辆行驶证
        licenseImage: [{
            defaultPath: '../../../images/car1.jpeg',
            path: '',
            name: 'drivingLicenseHomeFront',
            demo:'https://www.shencheyi.com/Files/TempletPhoto/DrivingPermitFront.jpg'
          },
          {
            defaultPath: '../../../images/car1-1.jpeg',
            path: '',
            name: 'drivingLicenseHomeReverse',
            demo:'https://www.shencheyi.com/Files/TempletPhoto/DrivingPermitReverse.jpg'
          }
        ],
      }, {
        registerImage: [{
          defaultPath: '../../../images/CertificateOfRegistration.jpeg',
            path: '',
            name: 'registrationFirstPage',
          demo:'https://www.shencheyi.com/Files/TempletPhoto/CertificateOfRegistration.jpg'
          },
          // {
          //   defaultPath: '../../../images/cardj3.png',
          //   path: '',
          //   name: 'registrationThirdlyPage'
          // },
          // {
          //   defaultPath: '../../../images/cardj4.png',
          //   path: '',
          //   name: 'registrationFourthlyPage'
          // },
        ]
      },
      {
        certificateImage: {
          defaultPath: '../../../images/car-ws.png',
          path: '',
          name: 'dutyPaidProof'
        }
      },
      {
        applicationImage: {
          defaultPath: '../../../images/car-down.png',
          path: '',
          name: 'dutyPaidProof'
        }
      }
    ],
    activeDot: 0,
    activeDotList: util.createDotList(totalDot, 0),
    showTopTips: false,
    errorMsg: "",
    config: {
      tipsshow1: "block",
    }

  },

  onLoad: function(e) {
    let templateDataList = this.data.templateDataList;
    this.uploadedImage = [];

    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              console.log('授权成功')
            }
          })
        }
      }
    });
    if (e.carId) {
      this.getCarInfo(e.carId)
        .then(res => {

          templateDataList[1].licenseImage.forEach(license => {
            license.path = res[license.name]
          });
          templateDataList[2].registerImage.forEach(register => {
            register.path = res[register.name]
          });
          templateDataList[3].certificateImage.path = res.certificateImage;
          templateDataList[0].carTypeName = res.carTypeName;
          templateDataList[0].carBelongType = res.carBelongType;
          templateDataList[0].licenceProvince = res.licencePlate.substr(0,1);
          templateDataList[0].licenceCode = res.licencePlate.substr(1);
          app.carTypeId = res.carTypeId;
          app.carBelongType = res.carBelongType;
          app.imageUrl = res.carPhoto;
          this.setData({
            carId: e.carId,
            carInfo: res,
            templateDataList: templateDataList
          });
        });

    }

  },

  onShow: function() {
    //加载车辆类型列表
    app.request('/CarType/carTypeList', 'GET', {},
      res => {
        this.resCarTypeList = res.list;
        this.setData({
          ['templateDataList[0].carTypeList']: res.list.map(item => {
            return item.name;
          })
        });
      });
  },

  //车牌键盘的输入触发
  inputPaneChange: function(e) {
    let licenceCode = this.data.templateDataList[0].licenceCode;
    if (this.data.templateDataList[0].keyBoardType == 1) {
      this.setData({
        ['templateDataList[0].isPanelShow']: false,
        ['templateDataList[0].licenceProvince']: e.detail,
      });
    } else {
      if (licenceCode.length >= 6 || !e.detail) {
        return;
      }
      this.setData({
        ['templateDataList[0].licenceCode']: `${licenceCode}${e.detail}`,
      });
    }
  },
  panelHide:function(){
    this.setData({
      ['templateDataList[0].isPanelShow']: false
    });
  },
  //车牌键盘删除触发
  inputPaneDelete: function() {
    let licenceCode = this.data.templateDataList[0].licenceCode.split('');
    licenceCode.pop();
    this.setData({
      ['templateDataList[0].licenceCode']: licenceCode.join(''),
    });
  },
  //车牌键盘确认触发
  inputPaneOk: function() {
    this.setData({
      ['templateDataList[0].isPanelShow']: false
    });
  },
  //显示车牌键盘
  onShowPanel: function(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      ['templateDataList[0].isPanelShow']: true,
      ['templateDataList[0].keyBoardType']: type,
    });
  },

  chooseImg: function() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.info(res.tempFilePaths.length);
        console.info(tempFilePaths);
        that.uploadFile2(tempFilePaths, 0);
      }
    })
  },

  uploadFile2: function(file, i) { //递归调用
    var that = this;
    wx.uploadFile({
      url: 'https://www.shencheyi.com/api/v1/Files/Img',
      filePath: file[i],
      name: 'file',
      success: function(res) {
        var obj = new Object();
        obj.ind = i + 1;
        var data = res.data;
        var resultData = JSON.parse(res.data);
        console.log("asd", resultData)
        that.setData({
          ['carInfo.carPhoto']: resultData.data.imgPath
        });
        var imageUrl = resultData.data.imgPath;
        app.imageUrl = imageUrl;
        console.log('照片链接', imageUrl)
      }
    })
  },

  onBindChange: function(e) {
    console.log(e);
    const name = e.currentTarget.dataset.name,
      value = parseInt(e.detail.value);
    if (name === 'carTypeName') {
      app.carTypeId = this.resCarTypeList[value].carTypeId;
      this.setData({
        [`templateDataList[0].${name}`]: this.resCarTypeList[value].name
      });
    } else {
      app.carBelongType = value;
      this.setData({
        [`templateDataList[0].${name}`]: value
      });
    }
  },

  // 提交第一步
  onFirstSubmit: function(e) {
    util.clearError(this);
    let postCarInfo = {},
      targetInfo = e.detail.value,
      licencePlate = this.data.templateDataList[0].licenceProvince + this.data.templateDataList[0].licenceCode,
      {
        // licencePlate,
        phoneNumber,
        owner,
        carDiscernCode,
        carEngineNumber,
        carSeats
      } = targetInfo;
    console.log(targetInfo);

    if (!this.checkInfoEdit(licencePlate, phoneNumber, owner, carDiscernCode, carEngineNumber, carSeats)) {
      return false;
    }

    postCarInfo = {
      userId: app.globalData.userId,
      licencePlate: licencePlate,
      carPhoto: app.imageUrl,
      carTypeId: app.carTypeId,
      carBelongType: app.carBelongType,
      owner: owner,
      phoneNumber: phoneNumber,
      carDiscernCode: carDiscernCode,
      carEngineNumber: carEngineNumber,
      carSeats: carSeats
    };

    if (this.data.carId) {
      Object.assign(postCarInfo, {
        carId: this.data.carId
      });
      this.submitFirst(postCarInfo)
        .then(this.nextStep);
    } else {
      this.createCarInfo(postCarInfo)
        .then(res => {
          Object.assign(postCarInfo, res);
          this.submitFirst(postCarInfo);
        })
        .then(res => {
          this.nextStep();
        });
    }
  },

  //提交第二三四步
  onImageSubmit: function(e) {
    util.clearError(this);
    const activeDot = this.data.activeDot,
      templateDataList = this.data.templateDataList;
    let imagesUploadPromises = [],
      curImages = null,
      curType = '';
    if (activeDot === 1) {
      curImages = templateDataList[1].licenseImage;
      curType = 'CarSecond';
    } else if (activeDot === 2) {
      curImages = templateDataList[2].registerImage;
      curType = 'CarThirdly';
    } else {
      curImages = templateDataList[3].certificateImage;
      curType = 'CarFourthly';
    }
    console.log('curImages', curImages);
    imagesUploadPromises = this.checkUploadImage(curImages);
    if (!imagesUploadPromises) {
      return;
    }
    console.log(imagesUploadPromises);
    if (imagesUploadPromises.length === 0) {
      if(this.data.activeDot == '2'){
        this.onAllComplete();
      }else{
        this.nextStep();
      }
      return;
    }

    //启动上传
    wx.showLoading({
      title: '正在上传...',
    });
    Promise.all(imagesUploadPromises)
      .then(res => {
        wx.hideLoading();
        this.saveUploadImage(curType, res);
      })
      .then(res => {
        console.log('here');
        if(this.data.activeDot == 2){
          this.onAllComplete();
        }else{
          this.nextStep();
        }
      })
      .catch(err => {
        wx.showToast({
          title: '上传失败',
          image: '../../../images/fail.png'
        });
      });

  },


  onAllComplete: function() {
    wx.showModal({
      title: '提示',
      content: '车辆绑定成功',
      showCancel: false,
      success: () => {
        wx.navigateBack();
      }
    });
  },

  //下载机动车申请表
  onDownloadApplication: function() {
    wx.showLoading({
      title: '下载中...',
    });
    wx.downloadFile({
      url: applicationDownPath,
      success: function(res) {
        var filePath = res.tempFilePath;
        console.log(filePath);
        wx.saveImageToPhotosAlbum({
          filePath: filePath,
          success: function(data) {
            console.log(data);
            wx.showToast({
              title: '已保存至相册',
            });
          },
          fail: function(err) {
            console.log(err);
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("用户一开始拒绝了，我们想再次发起授权")
              console.log('打开设置窗口')
              wx.openSetting({
                success(settingdata) {
                  console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                  } else {
                    console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                  }
                }
              });

            }
          }
        })
      },
      complete: function(res) {
        wx.hideLoading();
        console.log(res);
      }
    })
  },

  //选择照片
  onImageChoose: function(e) {
    if (!this.data.currentTapPic){
      return;
    }
    const targetId = this.data.currentTapPic,
      keyArray = ['', `templateDataList[1].licenseImage[${targetId}].path`, `templateDataList[2].registerImage[${targetId}].path`, `templateDataList[3].certificateImage.path`, `templateDataList[4].applicationImage.path`],
      activeDot = this.data.activeDot;
    this.closePicDemo()

    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      success: res => {
        console.log(res);
        this.setData({
          [keyArray[activeDot]]: res.tempFilePaths[0]
        });
      }
    })
  },

  //检测图片上传程度并添加至上传任务
  checkUploadImage: function(targetUploadImage) {
    let targetUploadImages = [],
      tempUploadImages = [],
      imagesUploadPromises = [];
    //规定参数必须为一个数组类型
    console.log('targetUploadImage', targetUploadImage);
    if (Object.prototype.toString.call(targetUploadImage) !== '[object Array]') {
      targetUploadImages.push(targetUploadImage);
    } else {
      tempUploadImages = targetUploadImage;
    }

    //检查图片本身是网络路径说明已上传过无需重新上传
    // tempUploadImages = JSON.parse(JSON.stringify(targetUploadImages));

    tempUploadImages.forEach((item, index) => {
      if (item.path.indexOf('https://www.') === -1) {
        targetUploadImages.push(item);
      } else {
        this.uploadedImage.push(item);
      }
    });
    console.log(targetUploadImages);
    //检测照片并逐一加入上传任务
    for (let i = 0; i < targetUploadImages.length; i++) {
      if (!targetUploadImages[i].path) {
        wx.showToast({
          title: `请上传照片第${i+1}张`,
          image: '../../../images/fail.png'
        });
        return false;
      } else {
        let target = new Promise((resolve, reject) => {
          wx.uploadFile({
            url: 'https://www.shencheyi.com/api/v1/Files/Img',
            filePath: targetUploadImages[i].path,
            name: targetUploadImages[i].name,
            success: res => {
              console.log(res);
              let param = {};
              param[targetUploadImages[i].name] = JSON.parse(res.data).data.imgPath
              resolve(param);
            },
            fail: err => {
              reject(err);
              return false;
            }
          });
        });
        imagesUploadPromises.push(target);
      }
    }
    return imagesUploadPromises;
  },

  //新增车辆，返回carId
  createCarInfo: function(postCartInfo) {
    return new Promise((resolve, reject) => {
      app.request('/Car/Create', 'POST', postCartInfo,
        res => {
          this.carId = res.carId;
          postCartInfo.carId = res.carId;
          resolve(res);
        }, '创建车辆失败');
    });
  },

  //保存车辆信息
  submitFirst: function(postCartInfo) {
    return new Promise((resolve, reject) => {
      console.log(postCartInfo);
      app.request('/Car/CarFirst', 'PUT', postCartInfo,
        res => {
          resolve(res);
        }, '保存车辆信息失败');
    });
  },

  //保存相关材料到服务器
  saveUploadImage: function(type, params) {
    let postInfo = {
      carId: this.carId || this.data.carId
    };
    //如果存在着已保存的网络图片
    if (this.uploadedImage.length !== 0) {
      this.uploadedImage.forEach(uploaded => {
        postInfo[uploaded.name] = uploaded.path;
      });
    }

    params.forEach(param => {
      Object.assign(postInfo, param);
    });
    console.log(postInfo);
    return new Promise((resolve, reject) => {
      app.request(`/Car/${type}`, 'PUT', postInfo,
        res => {
          resolve(res);
        }, err => {
          reject(err);
        });
    });
  },


  //检验输入车辆编辑信息
  checkInfoEdit: function(licencePlate, phoneNumber, owner, carDiscernCode, carEngineNumber, carSeats) {
    // if (licencePlate == '') {
    //   util.isError('请输入车牌号码', this);
    //   return false;
    // }
    if (!this.data.templateDataList[0].licenceProvince){
      util.isError('请输入车牌省份', this);
      return false;
    }
    if (!this.data.templateDataList[0].licenceCode){
      util.isError('请输入车牌号码', this);
      return false;
    }

    if (typeof(app.carTypeId) == "undefined") {
      util.isError('请选择车辆类型', this);
      return false;
    }
    if (phoneNumber == '' || !(/^1[34578]\d{9}$/.test(phoneNumber))) {
      util.isError('请输入正确的手机号码', this);
      return false;
    }

    if (owner == '') {
      util.isError('请输入车辆所属人', this);
      return false;
    }
    if (carDiscernCode == '') {
      util.isError('请输入车辆识别代码', this);
      return false;
    }
    if (carEngineNumber == '') {
      util.isError('请输入车辆发动机号', this);
      return false;
    }
    if (carSeats == '') {
      util.isError('请输入载客人数', this);
      return false;
    }

    return true;
  },

  //下一步骤切换的处理
  nextStep: function() {
    let activeDot = this.data.activeDot,
      nextDot = activeDot + 1;
    // 提交表单之后
    if (activeDot < totalDot - 1) {
      this.setData({
        activeDot: nextDot,
        activeDotList: util.createDotList(totalDot, nextDot)
      }, () => {
        wx.setNavigationBarTitle({
          title: `添加车辆-${templateListText[nextDot]}`
        })
      });
    }
  },

  //上一步
  prevStep: function() {
    let activeDot = this.data.activeDot,
      prevDot = activeDot - 1;
    // 提交表单之后
    if (activeDot < totalDot) {
      this.setData({
        activeDot: prevDot,
        activeDotList: util.createDotList(totalDot, prevDot)
      }, () => {
        wx.setNavigationBarTitle({
          title: `添加车辆-${templateListText[prevDot]}`
        })
      });
    }
  },

  //获取车辆信息
  getCarInfo: function(carId) {
    return new Promise((resolve, reject) => {
      app.request('/Car/Car', 'GET', {
          carId: carId,
          userId: app.globalData.userId
        },
        res => {
          resolve(res);
        }, '获取车辆信息失败');
    });
  },
  openPicDemo: function(e) {
    this.setData({
      currentTapPic:e.target.id,
      isShowDemo:true,
      demoSrc: e.currentTarget.dataset.demo
    })
  },

  closePicDemo: function() {
    this.setData({
      isShowDemo: false,
      currentTapPic: ''
    })
  }

})